package section5_2;

import java.util.List;
import java.util.concurrent.RecursiveAction;

/**
 * Created by Hyman on 2017/6/9.
 */
public class Task extends RecursiveAction {

    /**
     * 产品集合对象
     */
    private List<Product> productList;
    /**
     * 处理的第一个产品位置
     */
    private int first;
    /**
     * 处理的最后一个产品位置
     */
    private int last;
    /**
     * 价格增长额
     */
    private double increment;

    public Task(List<Product> products, int first, int last, double increment) {
        this.productList = products;
        this.first = first;
        this.last = last;
        this.increment = increment;
    }

    @Override
    protected void compute() {

        if(last - first < 10) {
            updatePrices();
        } else {
            int middle = (first + last) / 2;
            System.out.printf("Task: Pending tasks: %s\n", getQueuedTaskCount());
            Task t1 = new Task(productList, first, middle + 1, increment);
            Task t2 = new Task(productList, middle + 1, last, increment);
            invokeAll(t1, t2);
        }

    }

    /**
     * 更新价格，将指定的范围内的产品提价
     */
    private void updatePrices() {
        for (int i = first; i < last; i++) {
            Product product = productList.get(i);
            product.setPrice(product.getPrice() * (1 + increment));  // 按increment比率提价
        }
    }
}
